# -*- coding: utf-8 -*-
__author__ = 'paul'
from five import grok
from zope import interface
import json
from Acquisition import aq_inner, aq_parent
from Products.bpChatCustom.interfaces import IChatTheme
try:
    from five.grok import CodeView as View
except ImportError:
    from five.grok import View

from babble.client import utils
from Products.CMFCore.utils import getToolByName

class UserOnLine(View):
    grok.context(interface.Interface)
    grok.name("users_online")
    grok.layer(IChatTheme)

    def update(self):
        self.contexto=aq_inner(self.context)

    def render(self):
        listing = self.datos_contexto()
        pretty = json.dumps(listing)
        self.request.response.setHeader("Content-type", "application/json")
        self.request.response.setHeader('Access-Control-Allow-Origin', '*')
        return pretty

    def datos_contexto(self):
        usuarios=utils.get_online_members(self.context)

        serU=[]

        for us in usuarios:
            serU.append({
                "id":us.id,
                "fullname":us.getProperty('fullname'),
                "area":self.getAreaForUser(us.id)
                })

        if len(serU)>0:
            ava="true"
        else:
            ava="false"

        data = dict(
            usuarios = serU,
            available= ava
        )
        return data

    def getAreaForUser(self,idUser):
        """Devuelve a que departamente pertenece un usuario, o sea su grupo"""
        groups_tool = getToolByName(self.context, 'portal_groups')
        blakL=["ChatResponsables","Staff","AuthenticatedUsers","Administrators"]
        susGrupos=groups_tool.getGroupsByUserId(idUser)
        grupoPosta=""
        for grupo in susGrupos:
            if grupo.id not in blakL:
                grupoPosta=grupo.title_or_id()

        return grupoPosta